<template>
  <div>
    <el-card>
      <el-breadcrumb separator-class="el-icon-arrow-right" style="height: 45px">
        <el-breadcrumb-item :to="{path:'/'}">
          <span>首页</span>
        </el-breadcrumb-item>
        <el-breadcrumb-item>活动列表</el-breadcrumb-item>
        <el-breadcrumb-item>报名活动</el-breadcrumb-item>
      </el-breadcrumb>
      <el-row>
        <!--        报名活动-->
        <el-col :span="24">
          <!--            回答基本信息-->
          <el-form :model="team" ref="team" label-width="90px" class="base_form">
            <!--              小队名称-->
            <el-form-item
                label="小队名称"
                :rules="[{ required: true, message: '请填写小队名称', trigger: 'blur' },
                           { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur'}]"
                prop="name">
              <el-input placeholder="请输入队名"
                        size="small"
                        v-model="team.name"
                        style="width: 300px"
                        clearable/>
            </el-form-item>
            <!--              指导老师-->
            <el-form-item label="指导老师">
              <el-select
                  v-model="team.teacherId"
                  size="small"
                  style="width: 300px"
                  filterable
                  remote
                  reserve-keyword
                  placeholder="请输入职工号"
                  :remote-method="remoteMethodTeacher"
                  :loading="loading"
                  clearable>
                <el-option
                    v-for="item in teacherOptions"
                    :key="item.label"
                    :label="item.value + item.label"
                    :value="item.label">
                  <span style="float: left">{{ item.label }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item.value }}</span>
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="邀请队员">
              <el-select
                  v-model="team.memberIds"
                  size="small"
                  style="width: 300px"
                  multiple
                  filterable
                  remote
                  reserve-keyword
                  placeholder="请输入学号"
                  :remote-method="remoteMethod"
                  :loading="loading"
                  clearable>
                <el-option
                    v-for="item in options"
                    :key="item.label"
                    :label="item.value + item.label"
                    :value="item.label">
                  <span style="float: left">{{ item.label }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item.value }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>

          <!--                回答问题-->
          <el-divider/>
          <el-form :model="questions" ref="questions" class="question__box">
            <span class="question__title">填写信息</span>
            <!-- 填空题 -->
            <el-form-item
                v-for=" (ques,index) in questions"
                :prop="index+'.answer'"
                :rules="{required: true, message: '不能为空', trigger: 'change'}"
                :key="index"
            >
              <span class="question__name">{{ index + 1 }}.{{ ques.questionName }}</span>
              <br/>
              <el-input
                  v-if="ques.type===1"
                  size="small"
                  style="padding-top: 10px; width: 370px;"
                  v-model="ques.answer"
                  type="textarea"
                  autosize
                  show-word-limit
                  :placeholder=ques.hint>
              </el-input>
              <!-- 单选 -->
              <el-radio-group
                  text-color="#3a7e59"
                  fill="#3a7e59"
                  v-if="ques.type===2"
                  v-model="ques.answer"
              >
                <el-radio
                    style="height: 40px; line-height:40px; margin-left: 10px"
                    v-for="(opt,idx) in ques.options"
                    :key="idx"
                    :label="opt">
                  {{ opt }}
                </el-radio>
              </el-radio-group>
              <!-- 多选 -->
              <el-checkbox-group
                  text-color="#3a7e59"
                  fill="#3a7e59"
                  v-if="ques.type===3"
                  v-model="ques.answer">
                <el-checkbox
                    style="  margin-left: 10px"
                    v-for="(opt,idx) in ques.options"
                    :key="idx"
                    :label="opt">
                  {{ opt }}
                </el-checkbox>
              </el-checkbox-group>
              <!-- 判断 -->
              <el-radio
                  style="margin-left: 10px"
                  v-if="ques.type===4"
                  v-model="ques.answer"
                  label="0">正确
              </el-radio>
              <el-radio
                  v-if="ques.type===4"
                  v-model="ques.answer"
                  label="1">错误
              </el-radio>
            </el-form-item>
          </el-form>
        </el-col>
        <div class="submitButton">
          <el-button type="success" size="small" @click="submit">提交报名信息
          </el-button>
        </div>

        <!--        历史团队成员-->
        <el-col :span="10" style="display: none">
          <el-form class="groupMemo">
            <!--              标题、添加小组、删除小组-->
            <el-form-item>
              <input
                  value="我的历史"
                  disabled="true"
                  style="outline: none; border: 0; width: 100px; font-size: 16px"
              />

              <!--              <span>-->
              <!--                  <img :src="addUrl"-->
              <!--                       style="width: 30px;height: 30px;margin-left: 240px;cursor: pointer"-->
              <!--                       alt=""-->
              <!--                       @click="addTeams = true">-->
              <!--                </span>-->
              <!--              <span>-->
              <!--                  <img :src="deleteUrl"-->
              <!--                       style="width: 30px;height: 30px;margin-left: 40px;cursor: pointer"-->
              <!--                       alt=""-->
              <!--                       @click="deleteTeams = true">-->
              <!--                </span>-->
            </el-form-item>
            <!--              备忘录展示-->
            <el-form-item>
              <el-tree
                  :props="teamProps"
                  show-checkbox
                  highlight-current
                  :data="treeData">
                <span class="custom-tree-node" slot-scope="{ node, data }">
                <span>{{ node.label }}</span>
                <span>
                  <el-button
                      type="text"
                      size="mini"
                      @click="() => append(data)">
                    Append
                  </el-button>
                  <el-button
                      type="text"
                      size="mini"
                      @click="() => remove(node, data)">
                    Delete
                  </el-button>
                </span>
              </span>
              </el-tree>
            </el-form-item>

          </el-form>
          <!--            新增小队-->
          <el-dialog title="新增分组"
                     :visible.sync="addTeams"
                     append-to-body
                     :close-on-click-modal=false>
            <el-form :model="addTeam">
              <el-form-item
                  label="新增分组名称"
                  :rules="[{ required: true, message: '请填写分组名称', trigger: 'blur' },
                           { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur'}]"
                  prop="name">
                <el-input placeholder="请输入分组"
                          v-model="addTeam.teamName"
                          style="width: 221px"
                          clearable/>
              </el-form-item>
              <!--                选择队员-->
              <el-form-item label="选择分组成员"
                            :rules="{ required: true, message: '请填写分组名称', trigger: 'blur' }"
                            prop="teamPerson">
                <el-select
                    v-model="team.memberIds"
                    multiple
                    filterable
                    remote
                    reserve-keyword
                    placeholder="请输入学号"
                    :remote-method="remoteMethod"
                    :loading="loading"
                    clearable>
                  <el-option
                      v-for="item in options"
                      :key="item.label"
                      :label="item.value + item.label"
                      :value="item.label">
                    <span style="float: left">{{ item.label }}</span>
                    <span style="float: right; color: #8492a6; font-size: 13px">{{ item.value }}</span>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="addTeams = false">取 消</el-button>
              <el-button type="primary" @click="submitAdd">确 定</el-button>
            </div>
          </el-dialog>
          <!--            删除小队-->
          <el-dialog
              title="提示"
              :visible.sync="deleteTeams"
              width="30%"
              append-to-body>
            <span>确定要删除吗?</span>
            <span slot="footer" class="dialog-footer">
              <el-button @click="deleteTeams = false">取 消</el-button>
              <el-button type="primary" @click="deleteTeams = false">确 定</el-button>
  </span>
          </el-dialog>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>
<script>
import loading from "../../../loading";

export default {
  data() {
    return {
      addUrl: require('../../../assets/photos/addGroup.png'),
      deleteUrl: require('../../../assets/photos/deleteGroup.png'),
      //远程搜索循环的数组
      options: [],
      teacherOptions: [],
      loading: false,
      props: {
        label: 'name',
        children: 'zones',
        isLeaf: 'leaf',
      },
      //填写的队伍信息
      team: {
        name: '',
        teacherId: '',
        memberIds: [],
        answers: [],
        activityId: this.$route.params.activityId
      },
      //备忘录展示
      treeData: [],
      teamProps: {
        label: 'name',
        children: 'members'
      },
      //返回的所有题目集合
      questions: [{
        answers: [],
        hit: '',
        options: []
      }],
      timeout: null,
      addTeam: {
        teamName: '',
        teamPerson: []
      },
      addTeams: false,
      deleteTeams: false,
      activityId: this.$route.params.activityId,
    }
  },
  created() {
    // this.getHistoryTeams()
  },

  async activated() {
    await this.getActivityQuestion()
  },
  methods: {
    //获取活动问卷
    getActivityQuestion() {
      this.$axios.get(`${this.HOST}/activity/sign/questions`, {
        params: {
          activityId: this.activityId
        }
      }).then(res => {
        this.questions = res.data.data
        // console.log("qq", this.questions)

      })
    },
    //远程搜索学生
    remoteMethod(query) {
      let _that = this
      if (this.timer) {
        clearTimeout(this.timer);
      }
      if (query !== '') {
        _that.loading = true;
        this.$axios.get(`${this.HOST}userinfo/stu/simple?condition=${query}`)
            .then(res => {
              let info = res.data.data
              setTimeout(() => {
                _that.loading = false
                _that.options = info
              }, 1000);
            })
      } else {
        this.options = [];
      }
    },

    //远程搜索老师
    remoteMethodTeacher(query) {
      let _that = this
      if (this.timer) {
        clearTimeout(this.timer);
      }
      if (query !== '') {
        _that.loading = true;
        this.$axios.get(`${this.HOST}/userinfo/teacher/simple?condition=${query}`)
            .then(res => {
              let info = res.data.data
              setTimeout(() => {
                _that.loading = false
                _that.teacherOptions = info
              }, 1000);
            })
      } else {
        this.teacherOptions = [];
      }
    },

    createStateFilter(queryString) {
      return (state) => {
        return (state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },

    handleSelect(item) {
      console.log(item);
    },

    submit() {
      const _loading = loading(`活动报名中，请稍等...`);
      let _this = this;
      this.$refs['questions'].validate((res) => {
        if (res) {
          this.$refs['team'].validate((res) => {
            if (res) {
              this.team.answers = []
              this.questions.forEach(ques => {
                let ans = ques.answer;
                if (ans instanceof Array) {
                  ans = ans.join("，")
                }
                this.team.answers.push(ans)
              })
              // console.log(this.team)
              try {
                this.$axios.post(`${this.HOST}/activity/sign`, this.team).then(res => {
                  if (res.data.code === 200) {
                    this.$alert("报名成功！点击确定前往活动管理页面完善信息。", "报名成功！").then(() => {
                      this.$router.push("/activities/manage")
                    })
                  }
                })
              } finally {
                _loading.close()
              }
            }
          });
        }
      })
    },
    getHistoryTeams() {
      this.$axios.get(`${this.HOST}/group/list`).then(res => {
        const treeData = res.data.data;
        treeData.forEach(item => {
          item['name'] = item['remark']
        })
        this.treeData = treeData
        console.log(this.treeData)
      })
    },

    submitAdd() {
      this.$axios.post(`${this.HOST}/group/put`, {
        team: this.addTeam,
      }).then(res => {
        if (res.data.code === 200) {
          this.$message({
            message: '添加成功,记得及时填写活动策划!',
            type: 'success',
            offset: 90,
            duration: 1000
          });
          this.getHistoryTeams()
        }
      })
      this.addTeams = false
    },

    append(data) {
      const newChild = {id: id++, label: 'testtest', children: []};
      if (!data.children) {
        this.$set(data, 'children', []);
      }
      data.children.push(newChild);
    },

    remove(node, data) {
      const parent = node.parent;
      const children = parent.data.children || parent.data;
      const index = children.findIndex(d => d.id === data.id);
      children.splice(index, 1);
    },
  },
}
</script>
<style lang="less" scoped>
.box-card {
  width: 480px;
  height: 500px;
}

.el-form {
  padding-left: 10px;
}

.base_form {
  .el-form-item {
    margin-bottom: 15px;
  }
}

.question__title {
  display: block;
  font-size: 14px;
  font-weight: bold;
  margin-bottom: 20px;
}

.question__box {
  width: 90%;
  padding-left: 30px;
  margin-bottom: 100px;

  .question__name {
    font-size: 14px;
  }
}

/deep/ .el-radio__input.is-checked + .el-radio__label {
  color: #316a4b;
}

/deep/ .el-checkbox__input.is-checked + .el-checkbox__label {
  color: #316a4b;
}

/deep/ .el-checkbox__input.is-checked .el-checkbox__inner, .el-checkbox__input.is-indeterminate .el-checkbox__inner {
  border-color: #316a4b;
  background: #316a4b;
}

/deep/ .el-radio__input.is-checked .el-radio__inner {
  border-color: #316a4b;
  background: #316a4b;
}

/deep/
.submitButton {
  position: absolute;
  bottom: 50px;
  right: 50px;
}

.groupMemo {
  width: 400px;
}

/deep/ .el-button--success {
  background-color: #316a4b;

  &:focus {
    background-color: #3a7e59 !important;
  }
}

</style>
